import { useState, useMemo } from 'react'
import {
  Card,
  Select,
  Row,
  Col,
  Typography,
  Tag,
  List,
  Statistic,
  Alert,
  Space,
  Badge,
} from 'antd'
import {
  CalendarOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import dayjs from 'dayjs'
import {
  getAvailableYears,
  isYearDataAvailable,
  getYearStatistics,
  getHolidaysByYear,
} from '../utils/holidayUtils'

const { Title, Text } = Typography
const { Option } = Select

const HolidayInfo = () => {
  const [selectedYear, setSelectedYear] = useState(dayjs().year())

  // 获取可用年份
  const availableYears = useMemo(() => getAvailableYears(), [])

  // 获取当前选择年份的统计信息
  const yearStats = useMemo(() => {
    return getYearStatistics(selectedYear)
  }, [selectedYear])

  // 获取当前选择年份的节假日列表
  const holidays = useMemo(() => {
    return getHolidaysByYear(selectedYear)
  }, [selectedYear])

  // 按节假日名称分组
  const holidayGroups = useMemo(() => {
    const groups = {}
    holidays.forEach((holiday) => {
      if (!groups[holiday.name]) {
        groups[holiday.name] = []
      }
      groups[holiday.name].push(holiday)
    })
    return groups
  }, [holidays])

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ marginBottom: '24px' }}>
          <Title level={3} style={{ display: 'flex', alignItems: 'center' }}>
            <CalendarOutlined style={{ marginRight: '8px' }} />
            节假日信息管理
          </Title>

          <Space direction='vertical' size='large' style={{ width: '100%' }}>
            {/* 年份选择 */}
            <div>
              <Text strong>选择年份：</Text>
              <Select
                value={selectedYear}
                onChange={setSelectedYear}
                style={{ width: 120, marginLeft: '8px' }}
              >
                {availableYears.map((year) => (
                  <Option key={year} value={year}>
                    {year}年
                  </Option>
                ))}
              </Select>

              {!isYearDataAvailable(selectedYear) && (
                <Alert
                  message={`${selectedYear}年的节假日数据暂未加载`}
                  type='warning'
                  showIcon
                  style={{ marginTop: '8px' }}
                />
              )}
            </div>

            {/* 统计信息 */}
            {yearStats.available && (
              <Row gutter={[16, 16]}>
                <Col xs={24} sm={6}>
                  <Card size='small'>
                    <Statistic
                      title='配置天数'
                      value={yearStats.totalDays}
                      prefix={<CalendarOutlined />}
                      suffix='天'
                    />
                  </Card>
                </Col>
                <Col xs={24} sm={6}>
                  <Card size='small'>
                    <Statistic
                      title='放假天数'
                      value={yearStats.holidayDays}
                      prefix={
                        <CheckCircleOutlined style={{ color: '#52c41a' }} />
                      }
                      suffix='天'
                      valueStyle={{ color: '#52c41a' }}
                    />
                  </Card>
                </Col>
                <Col xs={24} sm={6}>
                  <Card size='small'>
                    <Statistic
                      title='调休工作日'
                      value={yearStats.workingDays}
                      prefix={
                        <ExclamationCircleOutlined
                          style={{ color: '#fa8c16' }}
                        />
                      }
                      suffix='天'
                      valueStyle={{ color: '#fa8c16' }}
                    />
                  </Card>
                </Col>
                <Col xs={24} sm={6}>
                  <Card size='small'>
                    <Statistic
                      title='节假日种类'
                      value={Object.keys(yearStats.holidays).length}
                      prefix={<InfoCircleOutlined />}
                      suffix='个'
                    />
                  </Card>
                </Col>
              </Row>
            )}

            {/* 节假日详细信息 */}
            {yearStats.available && (
              <Card title='节假日详细信息' size='small'>
                <List
                  dataSource={Object.entries(holidayGroups)}
                  renderItem={([holidayName, holidayList]) => {
                    const holidayDays = holidayList.filter((h) => h.isOffDay)
                    const workingDays = holidayList.filter((h) => !h.isOffDay)

                    return (
                      <List.Item>
                        <div style={{ width: '100%' }}>
                          <div
                            style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              marginBottom: '8px',
                            }}
                          >
                            <Title level={5} style={{ margin: 0 }}>
                              {holidayName}
                            </Title>
                            <Space>
                              {holidayDays.length > 0 && (
                                <Badge
                                  count={holidayDays.length}
                                  style={{ backgroundColor: '#52c41a' }}
                                  title='放假天数'
                                />
                              )}
                              {workingDays.length > 0 && (
                                <Badge
                                  count={workingDays.length}
                                  style={{ backgroundColor: '#fa8c16' }}
                                  title='调休工作日'
                                />
                              )}
                            </Space>
                          </div>

                          <div>
                            {/* 放假日期 */}
                            {holidayDays.length > 0 && (
                              <div style={{ marginBottom: '4px' }}>
                                <Text type='secondary'>放假：</Text>
                                {holidayDays.map((holiday) => (
                                  <Tag key={holiday.date} color='green'>
                                    {dayjs(holiday.date).format('MM-DD')}
                                  </Tag>
                                ))}
                              </div>
                            )}

                            {/* 调休工作日 */}
                            {workingDays.length > 0 && (
                              <div>
                                <Text type='secondary'>调休上班：</Text>
                                {workingDays.map((holiday) => (
                                  <Tag key={holiday.date} color='orange'>
                                    {dayjs(holiday.date).format('MM-DD')}
                                  </Tag>
                                ))}
                              </div>
                            )}
                          </div>
                        </div>
                      </List.Item>
                    )
                  }}
                />
              </Card>
            )}

            {/* 可用年份信息 */}
            <Card title='数据可用性' size='small'>
              <div>
                <Text strong>已加载的年份数据：</Text>
                <div style={{ marginTop: '8px' }}>
                  {availableYears.map((year) => (
                    <Tag
                      key={year}
                      color={year === selectedYear ? 'blue' : 'default'}
                      style={{ cursor: 'pointer' }}
                      onClick={() => setSelectedYear(year)}
                    >
                      {year}年
                    </Tag>
                  ))}
                </div>

                <Alert
                  message='系统说明'
                  description={
                    <div>
                      <p>
                        • 当前系统已加载 {availableYears.length}{' '}
                        个年份的节假日数据
                      </p>
                      <p>• 工时统计将根据对应年份的节假日配置自动计算工作日</p>
                      <p>• 调休工作日将按正常工作日计算8小时标准工时</p>
                      <p>• 如需其他年份数据，请联系管理员添加配置文件</p>
                    </div>
                  }
                  type='info'
                  showIcon
                  style={{ marginTop: '16px' }}
                />
              </div>
            </Card>
          </Space>
        </div>
      </Card>
    </div>
  )
}

export default HolidayInfo
